//
//  LCProudctListVC.m
//  stone-story
//
//  Created by dodo liu on 12-9-24.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
//

#import "LCProudctListVC.h"

@interface LCProudctListVC ()

@end

@implementation LCProudctListVC
@synthesize photos = _photos;
@synthesize product_type;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isEditMode=NO;
    indexcount=0;
    //[self.view setBackgroundColor:[UIColor grayColor]];
    
    [ self addNavBarRightBtn];
    if(dataArray==nil)
        dataArray=[[NSMutableArray alloc]init];
    
    
    [self setDataArrayByCategoryID:[NSNumber numberWithInt:[product_type intValue]]];
    NSLog(@"the product_type is=%@",product_type);
    [self tableView_init];
    
}
- (void)addNavBarRightBtn
{
    UIBarButtonItem *btn_1 = [[UIBarButtonItem alloc] initWithTitle:@"编辑"   
                                                              style:UIBarButtonItemStyleBordered   
                                                             target:self   
                                                             action:@selector(toEdit:)];  
    [btn_1 setTag:9901];
    [btn_1 setTintColor:[UIColor blackColor]];
    UIBarButtonItem *btn_2 = [[UIBarButtonItem alloc] initWithTitle:@"新品下载"
                                                              style:UIBarButtonItemStyleBordered 
                                                             target:self action:@selector(toDownLoad)];
    [btn_2 setTintColor:[UIColor redColor]];
    
    UIBarButtonItem *btn_3 = [[UIBarButtonItem alloc] initWithTitle:@"产品类别"
                                                              style:UIBarButtonItemStyleBordered 
                                                             target:self action:@selector(showPop)];
    [btn_3 setTintColor:[UIColor blackColor]];
    LCToolbar *tools = [[LCToolbar alloc] initWithFrame:CGRectMake(0, 0, 230, 45)];
    
    tools.barStyle=UIBarStyleDefault;
    //[tools setBackgroundColor:[UIColor clearColor]];
    buttons = [[NSMutableArray alloc] initWithCapacity:3];
    
    [buttons addObject:btn_1];
    [buttons addObject:btn_2];
    [buttons addObject:btn_3];
    [tools setItems:buttons animated:NO];
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:tools]; 
    
}
-(void)toDownLoad
{
    if(lp==nil)
    lp=[[LCProductDLVC alloc]init];
    lp._delegate=self;
    if(lp.finishDLProductIDArray==nil)
        lp.finishDLProductIDArray=[[NSMutableArray alloc]init];
    //lp.finishDLProductIDArray=[self getExsitProductIDArray];
    for(int i=0;i<[self getExsitProductIDArray].count;i++)
    {
        [lp.finishDLProductIDArray addObject:[[self getExsitProductIDArray] objectAtIndex:i]];
    }
    [self.navigationController pushViewController:lp animated:YES];
    /*
    //MyFirstViewController* firstVC = [[[MyFirstViewController alloc] initWithNibName:@"FirstNib" bundle:nil] autorelease];  
   // MySecondViewController* secondVC = [[[MySecondViewController alloc] initWithNibName:@"SecondNib" bundle:nil] autorelease];  
   // 
  */
    /*
    if(dlmgr_vc==nil)
        dlmgr_vc=[[LCProductDLMgr alloc] init];
    if(dl_vc==nil)
        dl_vc=[[LCProductDLVC alloc]init];
    
    UISplitViewController* splitVC = [[UISplitViewController alloc] init];   
    splitVC.viewControllers = [NSArray arrayWithObjects:dlmgr_vc, dl_vc, nil]; 
    //[self presentModalViewController:splitVC animated:YES];
    
    [self.view addSubview:splitVC.view];
   // [self presentModalViewController:splitVC animated:splitVC animated:YES];
    */
}
//下载页面的委托方法
-(void)refreshProductList
{
    [self setDataArrayByCategoryID:[NSNumber numberWithInt:[product_type intValue]]];
    [LCtableView reloadData];
}
//取得已经存在的productID
-(NSMutableArray*)getExsitProductIDArray
{
    NSMutableArray *exsitProductIDArray=[[NSMutableArray alloc]init];
    for(int i=0;i<dataArray.count;i++)
    {
        NSMutableDictionary *nd=[dataArray objectAtIndex:i];
        
        [exsitProductIDArray addObject:[nd valueForKey:@"product_id"]];
    }
    return exsitProductIDArray;
}
- (void)toEdit:(id)sender
{
    // Browser
    if(isEditMode)
    {
        if(deleteArray.count==0)//当没有选择要删除的产品时
        {
            UIAlertView* av2 = [[UIAlertView alloc]initWithTitle:nil 
                                                        message:@"请先选择要删除的产品?"
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles:nil];
            
            //[av setTag:10000+index];
            [av2 show]; 
        }
        else//选择了
        {
            UIAlertView* av = [[UIAlertView alloc]initWithTitle:nil 
                                                        message:@"是否删除所选产品?"
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"删除",nil];
            
            //[av setTag:10000+index];
            [av show];

        }
               
        
    }
    else {
        [sender setTitle:@"删除"];
        isEditMode=YES;
    }
    
    
}

- (void) alertView:(UIAlertView *)alertview clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%d",buttonIndex);
   
    if(buttonIndex==1)
    { 
        NSLog(@"现在要删除拉:%@", [deleteArray description]);
        [self deleteRecordWithProductIDArray:deleteArray];
        
        //[sender setTitle:@"编辑"];
        [deleteArray removeAllObjects];
        [self setDataArrayByCategoryID:[NSNumber numberWithInt:[product_type intValue]]];
        [LCtableView reloadData];
        isEditMode=NO;
        //UIBarButtonItem *bb=(UIBarButtonItem*)[self.view viewWithTag:9901];
        UIBarButtonItem *bb=[buttons objectAtIndex:0];
        [bb setTitle:@"编辑"];
    }
}


#pragma mark 相册部分
-(void)goToPhotoBrowserWithPath:(NSString*)pathString selfPhotos:(NSArray*)selfPhotos
{
    NSMutableArray *photos = [[NSMutableArray alloc] init];
    MWPhoto *photo;
    NSMutableArray *photosArray=[self getAllPhotosWithPath:pathString];
    for(int i=0;i<photosArray.count;i++)
    {
        //Documents/productPhotos/
        NSString *fullPath=[pathString stringByAppendingString:[photosArray objectAtIndex:i]];
        photo = [MWPhoto photoWithFilePath:[NSHomeDirectory() stringByAppendingPathComponent:fullPath]];
        //photo.caption = @"Grotto of the Madonna";
        [photos addObject:photo];
    }
    self.photos = photos;
	MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;
    //browser.wantsFullScreenLayout = NO;//[browser setInitialPageIndex:2];    
    [self.navigationController pushViewController:browser animated:YES];
}

- (NSMutableArray*)getAllPhotosWithPath:(NSString*)pathString
{
    
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:pathString];
     NSLog(@"the filePath is = %@",filePath);
    NSError *error = nil;
    NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:filePath error:&error];
    NSMutableArray *fileNames=[[NSMutableArray alloc]init];
    NSLog(@"%@", dirContents);
    if ( ! error) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self ENDSWITH[cd] '.jpg'"];
        NSArray *imagesOnly = [dirContents filteredArrayUsingPredicate:predicate];
         
        fileNames = [NSMutableArray arrayWithArray:imagesOnly];
    }
    //NSLog(@"photos count is=%d",[fileNames count]);
    // count = [fileNames count];  //得到数量多少
    return fileNames;
}
#pragma mark - 相册部分 委托

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return _photos.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    if (index < _photos.count)
        return [_photos objectAtIndex:index];
    return nil;
}





- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}

#pragma mark 数据表格
- (void)tableView_init 
{
    CGRect tableFrame=CGRectMake(20,0,984,704); //矩形结构
    LCtableView=[[UITableView alloc]initWithFrame:tableFrame]; //分配内存，设置样式
    [LCtableView setDelegate:self]; //设置代理
    [LCtableView setDataSource:self]; //设置数据源
    [LCtableView setBackgroundColor:[UIColor clearColor]];
    [LCtableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [LCtableView setAllowsSelection:NO];
    [self.view addSubview:LCtableView]; //添加到父视图
    
}

//返回有多少个Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return 1;
}
//返回行数
- (NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section { 
    return dataArray.count/5+1; 
    
}
//每个section的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return @"";
}

//指定行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 240.8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier"; 
    
    UITableViewCell *cell = [LCtableView dequeueReusableCellWithIdentifier: 
                             TableSampleIdentifier]; 
    
    if (cell == nil) { 
        cell = [[UITableViewCell alloc] 
                initWithStyle:UITableViewCellStyleSubtitle 
                reuseIdentifier:TableSampleIdentifier]; 
    } 
    else {
        //重用CELL时候清空 SUBviews
        for(UIView *view in [cell.contentView subviews])
        {
            [view removeFromSuperview];
        }
    }
    
    cell.contentView.backgroundColor=[UIColor clearColor];
    NSMutableDictionary *nd;
    //创建按钮
    int item_one=[indexPath row]*5;
    int item_tow=item_one+1;
    int item_three=item_one+2;
    int item_four=item_one+3;
    int item_five=item_one+4;
    if(item_one<[dataArray count])
    {
        nd=[dataArray objectAtIndex:item_one];
        UIButton *itemOne=[[UIButton alloc]initWithFrame:CGRectMake(150*0+1*40.8,20.4,150,200)];
        [itemOne addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        [itemOne setTag:7000+item_one];
        [itemOne setImage:[self getLogoImageByFileName:[nd valueForKey:@"product_logo"]] forState:UIControlStateNormal];
        [cell.contentView addSubview:itemOne];
        
        //产品名称
        UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(itemOne.frame.origin.x,itemOne.frame.origin.y+itemOne.frame.size.height,150,25)] ;
        [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
        [productName setTextColor:[UIColor whiteColor]];
        [productName setNumberOfLines:1]; 
        [productName setBackgroundColor:[UIColor clearColor]]; 
        [productName setText:[nd  objectForKey:@"product_name"]];
        [productName setNumberOfLines:2]; 
        [productName setTextAlignment:UITextAlignmentCenter];
        [cell.contentView addSubview:productName];
        
        
        UIImageView *deleteFlagIV=[[UIImageView alloc]initWithFrame:CGRectMake(50, 60, 50, 50)];
        [deleteFlagIV setImage:[UIImage imageNamed:@"deleteBtn.png"]];
        [deleteFlagIV setTag:8000+item_one];
        [itemOne addSubview:deleteFlagIV];
        if(![deleteArray containsObject:[nd valueForKey:@"product_id"]])
            [deleteFlagIV setHidden:YES];
        else {
            [deleteFlagIV setHidden:NO];
        }
    
        indexcount++;
    }
    if(item_tow<[dataArray count])
    {
        nd=[dataArray objectAtIndex:item_tow];
        UIButton *itemTow=[[UIButton alloc]initWithFrame:CGRectMake(150*1+2*40.8, 20.4, 150, 200)];
         [itemTow addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        [itemTow setTag:7000+item_tow];

        
        [itemTow setImage:[self getLogoImageByFileName:[nd valueForKey:@"product_logo"]] forState:UIControlStateNormal];
         [cell.contentView addSubview:itemTow];
        
        //产品名称
        UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(itemTow.frame.origin.x,itemTow.frame.origin.y+itemTow.frame.size.height,150,25)] ;
        [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
        [productName setTextColor:[UIColor whiteColor]];
        [productName setNumberOfLines:1]; 
        [productName setBackgroundColor:[UIColor clearColor]]; 
        [productName setText:[nd  objectForKey:@"product_name"]];
        [productName setNumberOfLines:2]; 
        [productName setTextAlignment:UITextAlignmentCenter];
        [cell.contentView addSubview:productName];
        
        UIImageView *deleteFlagIV=[[UIImageView alloc]initWithFrame:CGRectMake(50, 60, 50, 50)];
        [deleteFlagIV setImage:[UIImage imageNamed:@"deleteBtn.png"]];
        [deleteFlagIV setTag:8000+item_tow];
        [itemTow addSubview:deleteFlagIV];
        if(![deleteArray containsObject:[nd valueForKey:@"product_id"]])
            [deleteFlagIV setHidden:YES];
        else {
            [deleteFlagIV setHidden:NO];
        }

        
        indexcount++;
    }
    
    if(item_three<[dataArray count])
    {   
        
        
        nd=[dataArray objectAtIndex:item_three];
        UIButton *itemThree=[[UIButton alloc]initWithFrame:CGRectMake(150*2+3*40.8, 20.4, 150, 200)];
         [itemThree addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
         [itemThree setTag:7000+item_three];
         [cell.contentView addSubview:itemThree];
         [itemThree setImage:[self getLogoImageByFileName:[nd valueForKey:@"product_logo"]] forState:UIControlStateNormal];
        
        //产品名称
        UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(itemThree.frame.origin.x,itemThree.frame.origin.y+itemThree.frame.size.height,150,25)] ;
        [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
        [productName setTextColor:[UIColor whiteColor]];
        [productName setNumberOfLines:1]; 
        [productName setBackgroundColor:[UIColor clearColor]]; 
        [productName setText:[nd  objectForKey:@"product_name"]];
        [productName setNumberOfLines:2]; 
        [productName setTextAlignment:UITextAlignmentCenter];
        [cell.contentView addSubview:productName];
        
  
        UIImageView *deleteFlagIV=[[UIImageView alloc]initWithFrame:CGRectMake(50, 60, 50, 50)];
        [deleteFlagIV setImage:[UIImage imageNamed:@"deleteBtn.png"]];
        [deleteFlagIV setTag:8000+item_three];
        [itemThree addSubview:deleteFlagIV];
        if(![deleteArray containsObject:[nd valueForKey:@"product_id"]])
            [deleteFlagIV setHidden:YES];
        else {
            [deleteFlagIV setHidden:NO];
        }
        indexcount++;
    }
    
    if(item_four<[dataArray count])
    {
        nd=[dataArray objectAtIndex:item_four];
        UIButton *itemFour=[[UIButton alloc]initWithFrame:CGRectMake(150*3+4*40.8, 20.4, 150, 200)];
         [itemFour addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        [itemFour setTag:7000+item_four];
        [itemFour setImage:[self getLogoImageByFileName:[nd valueForKey:@"product_logo"]] forState:UIControlStateNormal];
         [cell.contentView addSubview:itemFour];
        
        //产品名称
        UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(itemFour.frame.origin.x,itemFour.frame.origin.y+itemFour.frame.size.height,150,25)] ;
        [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
        [productName setTextColor:[UIColor whiteColor]];
        [productName setNumberOfLines:1]; 
        [productName setBackgroundColor:[UIColor clearColor]]; 
        [productName setText:[nd  objectForKey:@"product_name"]];
        [productName setNumberOfLines:2]; 
        [productName setTextAlignment:UITextAlignmentCenter];
        [cell.contentView addSubview:productName];
       
        UIImageView *deleteFlagIV=[[UIImageView alloc]initWithFrame:CGRectMake(50, 60, 50, 50)];
        [deleteFlagIV setImage:[UIImage imageNamed:@"deleteBtn.png"]];
        [deleteFlagIV setTag:8000+item_four];
        [itemFour addSubview:deleteFlagIV];
        if(![deleteArray containsObject:[nd valueForKey:@"product_id"]])
            [deleteFlagIV setHidden:YES];
        else {
            [deleteFlagIV setHidden:NO];
        }
        
        
        indexcount++;
    }
    
    if(item_five<[dataArray count])
    {
        nd=[dataArray objectAtIndex:item_five];
        UIButton *itemFive=[[UIButton alloc]initWithFrame:CGRectMake(150*4+5*40.8, 20.4, 150, 200)];
        [itemFive addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchUpInside];
        [itemFive setTag:7000+item_five];
        [itemFive setImage:[self getLogoImageByFileName:[nd valueForKey:@"product_logo"]] forState:UIControlStateNormal];
        [cell.contentView addSubview:itemFive];
        
        //产品名称
        UILabel *productName=[[UILabel alloc]initWithFrame:CGRectMake(itemFive.frame.origin.x,itemFive.frame.origin.y+itemFive.frame.size.height,150,25)] ;
        [productName setFont:[UIFont fontWithName:@"Thonburi-Bold" size:14.0]];
        [productName setTextColor:[UIColor whiteColor]];
        [productName setNumberOfLines:1]; 
        [productName setBackgroundColor:[UIColor clearColor]]; 
        [productName setText:[nd  objectForKey:@"product_name"]];
        [productName setNumberOfLines:2]; 
        [productName setTextAlignment:UITextAlignmentCenter];
        [cell.contentView addSubview:productName];
        
        UIImageView *deleteFlagIV=[[UIImageView alloc]initWithFrame:CGRectMake(50, 60, 50, 50)];
        [deleteFlagIV setImage:[UIImage imageNamed:@"deleteBtn.png"]];
        [deleteFlagIV setTag:8000+item_four];
        [itemFive addSubview:deleteFlagIV];
        if(![deleteArray containsObject:[nd valueForKey:@"product_id"]])
            [deleteFlagIV setHidden:YES];
        else {
            [deleteFlagIV setHidden:NO];
        }
        
        
        indexcount++;
    }
    
    return cell; 
}
//点击行事件 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

- (void)itemClick:(id)sender{
    NSLog(@"%d",[sender tag]-7000 );
    if(!isEditMode)
    {
    NSMutableDictionary *nd=[dataArray objectAtIndex:[sender tag]-7000];
    NSString *filePath =@"Documents/products/";
    NSString *fullPath=[filePath stringByAppendingPathComponent:[nd valueForKey:@"product_id"]] ;
    fullPath=[fullPath stringByAppendingString:@"/"];
    NSLog(@"the fullPath is = %@",fullPath);
    [self goToPhotoBrowserWithPath:fullPath selfPhotos:self.photos];
    }
    else 
    {
        [sender setAlpha:0.6];
        UIImageView *df=(UIImageView*)[self.view viewWithTag:[sender tag]+1000];
        [df setHidden:NO];
        
        if(deleteArray==nil)
            deleteArray=[[NSMutableArray alloc]init];
        if(![deleteArray containsObject:[productIDArray objectAtIndex:[sender tag]-7000]])
        [deleteArray addObject:[productIDArray objectAtIndex:[sender tag]-7000]];
    
    }
   
}
//根据logo路径和文件名获得image
-(UIImage*)getLogoImageByFileName:(NSString*)logoFileName
{
    NSString *filePath =[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/products/logo"];
    UIImage *logoImage=[UIImage imageWithContentsOfFile:[filePath stringByAppendingPathComponent:logoFileName]];
    return logoImage;
}
//根据产品类别id，从sqlite获得产品信息数组
-(void)setDataArrayByCategoryID:(NSNumber*)categoryid
{
    [self FMDB_init];
    [self queryTableFillArray:dataArray theCategoryID:categoryid];
}

//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
}

//查询
- (void)queryTableFillArray:(NSMutableArray*)array theCategoryID:(NSNumber*)category_id
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    [array removeAllObjects];
    if(productIDArray==nil)
        productIDArray=[[NSMutableArray alloc]init];
    [productIDArray removeAllObjects];
    
    if(logoArray==nil)
        logoArray=[[NSMutableArray alloc]init];
    [logoArray removeAllObjects];
    //返回全部查询结果
    FMResultSet *rs=[db executeQuery:@"SELECT * FROM Products WHERE product_type = ? ORDER BY product_id ASC",category_id];
    
    //rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
    int i=0;
    while ([rs next]){
        NSLog(@"\n product_type:%@ \n product_id:%@\n \n product_name:%@ \n product_logo:%@ \n product_price:%@ \n product_purchase:%@ \n product_wholesale:%@",[rs stringForColumn:@"product_type"],[rs stringForColumn:@"product_id"],[rs stringForColumn:@"product_name"],[rs stringForColumn:@"product_logo"],[rs stringForColumn:@"product_price"],[rs stringForColumn:@"product_purchase"],[rs stringForColumn:@"product_wholesale"]);
        
        NSMutableDictionary *nd=[[NSMutableDictionary alloc]init];
        
        [nd setValue:[rs stringForColumn:@"product_type"] forKey:@"product_type"];
        [nd setValue:[rs stringForColumn:@"product_id"] forKey:@"product_id"];
        [nd setValue:[rs stringForColumn:@"product_name"] forKey:@"product_name"];
        [nd setValue:[rs stringForColumn:@"product_logo"] forKey:@"product_logo"];
        [nd setValue:[rs stringForColumn:@"product_price"] forKey:@"product_price"];
        [nd setValue:[rs stringForColumn:@"product_purchase"] forKey:@"product_purchase"];
        [nd setValue:[rs stringForColumn:@"product_wholesale"] forKey:@"product_wholesale"];
        [array addObject:nd];//插入数组
        
      
        [productIDArray addObject:[rs stringForColumn:@"product_id"]];
         [logoArray addObject:[rs stringForColumn:@"product_logo"]];
        i++;
    }
    NSLog(@"共有%d产品记录",i);
    [rs close];
    [db close];
}


//更新数据 将“张三”更改为“李四”
-(void)updateRecord
{
    
    [db executeUpdate:@"UPDATE User SET Name = ? WHERE Name = ? ",@"李四",@"张三"];
    
}


//删除数据
- (void)deleteRecordWithProductIDArray:(NSMutableArray*)productID_Array
{
    [self FMDB_init];
    for(int i=0;i<productID_Array.count;i++){
       int product_id=[[productIDArray objectAtIndex:i]intValue];
       [db executeUpdate:@"DELETE FROM Products WHERE product_id = ?",[NSNumber numberWithInt:product_id]];
        [LCFileManager deleteFloderInPath:@"Documents/products/" FolderName:[productIDArray objectAtIndex:i]];
       [LCFileManager deleteFileInPath:@"Documents/products/logo/" FileName:[logoArray objectAtIndex:i]];
    }
}

#pragma mark - showPOP
//产品按钮触发事件
-(void)showPop
{
    popTableVC=[[PopoverTableVC alloc] initWithStyle:UITableViewStylePlain];
    popTableVC.delegate=self;
    
    //首先弹出的是 父类ID为0的VC
    popTableVC.parentcategroyID=@"0";
    
    UINavigationController *navController =[[UINavigationController alloc] initWithRootViewController: popTableVC];
    
    
    
    popover = [[UIPopoverController alloc] initWithContentViewController:navController];
    [popover setDelegate:self];
    [popover setPopoverContentSize:CGSizeMake(250,600)];
    popTableVC.contentSizeForViewInPopover=popTableVC.view.bounds.size;
    [popover presentPopoverFromRect:CGRectMake(950, 0, 10, 10) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController*)popoverController{
    if (popover) {
        [popover dismissPopoverAnimated:YES];
        // [popover release];
        popover=nil;
        if (popTableVC != nil) {
            // [popoverContent release];
            popTableVC = nil;
        }
    }
}
-(void)killPopoversOnSight {
    if (popover) {
        [popover dismissPopoverAnimated:NO];
    }
}

#pragma 实现PopoverTableVCDelegate 代理方法

- (void)PopoverTableVCDoneAction:(NSString *)name 
{
    [popover dismissPopoverAnimated:NO];
    [self setDataArrayByCategoryID:[NSNumber numberWithInt:[name intValue]]];
    [LCtableView reloadData];
   // NSLog(@"the product_type is=%@",product_type);
}


@end
